package com.fp.m7.client.place;

import net.customware.gwt.presenter.client.gin.ProvidedPresenterPlace;
import net.customware.gwt.presenter.client.place.PlaceRequest;

import com.fp.m7.client.presenter.LoginPresenter;
import com.google.inject.Inject;
import com.google.inject.Provider;

/**
 * Place where user enters his/her credentials to log into system. The 'error' param is supposed to be used by spring
 * redirection to indicate that user has entered wrong credentials.
 * 
 * @author 7
 */
public class LoginPlace extends ProvidedPresenterPlace<LoginPresenter> {

    public static final String NAME = "login";
    // params:
    public static final String ERROR = "error";
    public static final String DENIED = "denied";
    public static final String LOGOUT_SUCCESS = "logoutSuccess";
    public static final String SESSION_EXPIRED = "sessionExpired";

    private String error;

    @Inject
    public LoginPlace(Provider<LoginPresenter> presenter) {
        super(presenter);
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    protected void preparePresenter(PlaceRequest request, LoginPresenter presenter) {
        error = request.getParameter(ERROR, null);
        if (error != null) {
            try {
                Boolean errorParsed = Boolean.valueOf(error);
                if (errorParsed) {
                    presenter.setError(true);
                }
            } catch (NumberFormatException nfe) {
                // do not mind
            }
        }

        if (request.getParameter(LOGOUT_SUCCESS, null) != null) {
            presenter.logoutSuccess();
        } else if (request.getParameter(DENIED, null) != null) {
            presenter.accessDenied();
        } else if (request.getParameter(SESSION_EXPIRED, null) != null) {
            presenter.sessionExpired();
        }
    }

    @Override
    protected PlaceRequest prepareRequest(PlaceRequest request, LoginPresenter presenter) {
        if (error != null) {
            request = request.with(ERROR, error);
        }
        return request;
    }

}
